

#include <iostream>
using namespace std;
#include <string.h>

#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <unistd.h>

const string pathName = "home/linux/pathname";
const int pro_id = 0500;

struct mymsgbuf
{
    long mtype;
    char mtext[100];
};

int main()
{
    // 创建消息队列
    key_t key = ftok(pathName.c_str(), pro_id);
    // 创建时，仍然要设置权限，否则无法操作该消息队列
    int mesid = msgget(key, IPC_CREAT | IPC_EXCL | 0600);
    if (mesid == -1)
        cout << "创建消息队列失败" << endl;
    else
        cout << "创建成功,id:" << mesid << endl;

    // 发送消息
    int n = 10;
    while (n--)
    {
        struct mymsgbuf buf; // 创建系统提供的struct msgbuf类型的数据块
        if (n % 2 == 1)
            buf.mtype = 1;
        else
            buf.mtype = 2;
        strncpy(buf.mtext, "Hello World", sizeof(buf.mtext) - 1);
        buf.mtext[sizeof(buf.mtext) - 1] = '\0'; // 确保以空字符结尾

        int n = msgsnd(mesid, &buf, sizeof(buf.mtext), 0);
        if (n == -1)
            cout << "发送失败" << endl;
        else
            cout << "发送成功" << ",消息类型：" << buf.mtype << endl;
        sleep(1);
    }

    // 接收消息
    n = 10;
    while (n--)
    {
        struct mymsgbuf buffer;
        size_t sz = msgrcv(mesid, &buffer, sizeof(buffer), 1, 0);
        if (sz == -1)
            cout << "接收失败" << endl;
        else
            cout << "接收成功! " << buffer.mtext << "消息类型：" << buffer.mtype << endl;
    }

    // 销毁消息队列
    int ret = msgctl(mesid, IPC_RMID, nullptr);
    if (ret == -1)
        cout << "销毁消息队列失败" << endl;
    else
        cout << "销毁消息队列成功" << endl;
    return 0;
}
